﻿using Hangfire;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.BackgroundJobs.Hangfire;
using XDQ.VAT.Web.BackgroundJobs;

namespace Hangfire
{
    public static class BackgroundJobExtends
    {
        /// <summary>
        /// 后台作业进入周期性队列
        /// </summary>
        /// <typeparam name="TArgs">作业参数类型</typeparam>
        /// <param name="backgroundJobManager">后台作业管理器</param>
        /// <param name="cron">Cron表达式</param>
        /// <param name="args">作业参数</param>
        /// <param name="timeZone">时区信息。默认是Local，使用Windows时区</param>
        /// <returns></returns>
        public static Task EnqueueAsync<TArgs>(
            this IBackgroundJobManager backgroundJobManager,
            [NotNull] string cron,
            TArgs args,
            TimeZoneInfo timeZone = null
        )
        {
            Check.NotNullOrWhiteSpace(cron, nameof(cron));
            Check.NotNull(args, nameof(args));
            if (timeZone == null)
            {
                timeZone = TimeZoneInfo.Local;
            }
            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Unix:
                    string tz = TimeZoneConverter.TZConvert.WindowsToIana(timeZone.Id);
                    timeZone = TimeZoneConverter.TZConvert.GetTimeZoneInfo(tz);
                    break;
            }
            var jobName = BackgroundJobNameAttribute.GetName<TArgs>();
            Console.WriteLine($"添加/修改任务 {jobName}");
            RecurringJob.AddOrUpdate<MyAdapter<TArgs>>(jobName, adapter => adapter.ExecuteAsync(args), cron, timeZone, HangfireOptions.QueueName);

            return Task.CompletedTask;
        }

        class MyAdapter<TArgs> : HangfireJobExecutionAdapter<TArgs>
        {
            public MyAdapter(IOptions<AbpBackgroundJobOptions> options, IBackgroundJobExecuter jobExecuter, IServiceScopeFactory serviceScopeFactory, ILogger<Type> logger) : base(options, jobExecuter, serviceScopeFactory)
            {
                Logger = logger;
            }

            public ILogger<Type> Logger { get; }

            public new Task ExecuteAsync(TArgs args)
            {
                string now = DateTime.Now.ToString("HH:mm:ss.fff");
                Logger.LogInformation($"运行任务@{now}");
                return base.ExecuteAsync(args);
            }
        }
    }
}
